# import re
# import numpy as np
# s=[1,4]
# a=np.array(s)
# print(a)
# print('1',end='')
# print(' ',end='')
# print('2',end='')

# a=''
# print(bool(a))
# def Plot_line_test(self):
#     # self.gv_visual_data_content.fig1.clear()#绘图前先清除
#     # self.gv_visual_data_content.draw()#刷新然后重新绘图
#     xpoint = self.ui.XTextEdit.toPlainText()
#     ypoint = self.ui.YTextEdit.toPlainText()
#
#     xpoints = np.array(list(map(int, xpoint.split())))
#     ypoints = np.array(list(map(int, ypoint.split())))
#
#     print('xpoint', xpoints)
#     print('ypoint', ypoints)
#     print(type(xpoints))
#
#     self.gv_visual_data_content.fig1.plot(xpoints, ypoints)
#     self.gv_visual_data_content.fig1.set_title('plot')
#     self.graphic_scene = QGraphicsScene()
#     self.graphic_scene.addWidget(self.gv_visual_data_content)
#     self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
#     self.ui.graphicsView.show()

#plot 当缺少其中一位坐标时 已摒弃
# # plt.plot(xpoints, ypoints)
        # elif xpoint or ypoint == '':
        #     if xpoint == '':
        #         print('1')
        #         self.gv_visual_data_content.fig1.plot(ypoints)
        #         self.gv_visual_data_content.fig1.set_title('ploty')
        #         self.graphic_scene = QGraphicsScene()
        #         self.graphic_scene.addWidget(self.gv_visual_data_content)
        #         self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
        #         self.ui.graphicsView.show()
        #         # plt.plot(ypoints)
        #     else:
        #         print(3)
        #         self.gv_visual_data_content.fig1.plot(xpoints)
        #         self.gv_visual_data_content.fig1.set_title('plotx')
        #         self.graphic_scene = QGraphicsScene()
        #         self.graphic_scene.addWidget(self.gv_visual_data_content)
        #         self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
        #         self.ui.graphicsView.show()
        #         # plt.plot(xpoints)
# Line_Color = {'蓝色': 'b', '黑色': 'k', '绿色': 'g', '黄色': 'y', '红色': 'r', '白色': 'w', '洋红色': 'm', '青绿色': 'c'}
# Color_select ='蓝色'
# Color_push = Line_Color[Color_select]
# print(Color_push)
#
# from PySide2.QtWidgets import QApplication, QMessageBox, QFileDialog, QGraphicsScene
# from PySide2.QtUiTools import QUiLoader
#
# import matplotlib
# import numpy as np
# from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
# import matplotlib.pyplot as plt
#
# matplotlib.use("Qt5Agg")  # 声明使用QT5
#
#
# class MyFigureCanvas(FigureCanvas):
#     """
#     通过继承FigureCanvas类，使得该类既是一个PyQt5的Qwidget，又是一个matplotlib的FigureCanvas，这是连接pyqt5与matplotlib的关键
#     """
#
#     def __init__(self, parent=None, width=10, height=5, xlim=(0, 2500), ylim=(-2, 2), dpi=100):
#         # 初始化时将图片的长、宽、像素均初始化给定
#         # 其中xlim，ylim 表示横纵坐标的显示范围
#         # 创建一个Figure
#         self.figure = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
#         FigureCanvas.__init__(self, self.figure)  # 初始化父类
#         self.setParent(parent)
#
#         self.fig1 = self.figure.add_subplot(111)  # 添加子图
#         # add_subplot(2,2,4) 添加子图函数，三个参数分别表示纵向分几个子图，横向分几个子图，当前为第几个子图
#         self.fig1.spines['top'].set_visible(False)  # 去掉绘图时上面的横线
#         self.fig1.spines['right'].set_visible(False)  # 去掉绘图时右面的横线
#         self.fig1.set_xlim(xlim)
#         self.fig1.set_ylim(ylim)
#
#
# class Win_Main():
#     def __init__(self):
#         self.ui = QUiLoader().load("ui/EP.ui")  # 注意是对ui实例化
#
#         self.gv_visual_data_content = MyFigureCanvas(width=self.ui.graphicsView.width() / 100,
#                                                      height=self.ui.graphicsView.height() / 100,
#                                                      xlim=(0, 2 * np.pi),
#                                                      ylim=(-1, 1)
#                                                      )
#
#         self.plot_cos()
#         self.ui.btn_sin.clicked.connect(self.plot_sin)
#         self.ui.btn_cos.clicked.connect(self.plot_cos)
#
#     def plot_cos(self):
#         x = np.arange(0, 2 * np.pi, np.pi / 100)
#         y = np.cos(x)
#         self.gv_visual_data_content.fig1.plot(x, y)  # 在加在的图形gv_visual_data_content中的子图fig1中画图
#         self.gv_visual_data_content.fig1.set_title('cos()')  # 设置图名
#         self.graphic_scene = QGraphicsScene()  # 创建一个QGraphicsScene
#         # 加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
#         self.graphic_scene.addWidget(self.gv_visual_data_content)
#         # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到放到QGraphicsScene中的
#         self.ui.graphicsView.setScene(self.graphic_scene)  # 把QGraphicsScene放入QGraphicsView
#         self.ui.graphicsView.show()  # 调用show方法呈现图形
#
#     def plot_sin(self):
#         x = np.arange(0, 2 * np.pi, np.pi / 100)
#         y = np.sin(x)
#         self.gv_visual_data_content.fig1.clear()  # 由于图片需要反复绘制，所以每次绘制前清空，然后绘图
#         self.gv_visual_data_content.fig1.plot(x, y)
#         self.gv_visual_data_content.fig1.set_title('sin()')
#         self.gv_visual_data_content.draw()  # 刷新画布显示图片，否则不刷新显示
#
#
# app = QApplication([])
# LoginWin = Win_Main()
# LoginWin.ui.show()
# app.exec_()


class FrameRenderer():

    simulation = None
    scene = None
    timer = None

    def __init__(self, simulation, scene):
        self.simulation = simulation
        self.scene = scene
        self.timer = QTimer()
        self.timer.timeout.connect(self.nextFrame)
        self.timer.setInterval(1000/30)# 30 Frames per second

    #Render one time step
    def nextFrame(self):
        for food in self.simulation.food:
            food.xPos = food.xPos + randint(-1,1)
            food.yPos = food.yPos + randint(-1,1)
            if food.pixmap:
                food.pixmap.setPos(food.xPos, food.yPos)

    def start(self):
        self.timer.start()

    def pause(self):
        self.timer.stop()



class SimulationView():

    mainWindow = None
    graphicsScene = None
    simWindow = None
    simulation = None
    isSimulating = False
    simulationStarted = False
    frameRenderer = None
    beginSimulationButton = None
    cancelSimulationButton = None
    toggleSimulationButton = None
    foodSlider = None
    BUFFER = 10 #ensure we don't drop items too close to the extremes of the scene


    def __init__(self, mainWindow):

        self.mainWindow = mainWindow

        self.simWindow = mainWindow.simulation_window

        #connect QWidgets to functions
        self.beginSimulationButton = mainWindow.begin_simulation_button
        self.beginSimulationButton.clicked.connect(self.simulate)

        self.cancelSimulationButton = mainWindow.cancel_simulation_button
        self.cancelSimulationButton.clicked.connect(self.cancelSimulation)

        self.toggleSimulationButton = mainWindow.toggle_simulation_button
        self.toggleSimulationButton.clicked.connect(self.toggleSimulation)

        self.foodSlider = mainWindow.food_slider

    def createGraphicsScene(self):
        #create new scene
        self.graphicsScene = QGraphicsScene()
        self.graphicsScene.setSceneRect(self.simWindow.x(), self.simWindow.y(), self.simWindow.width() - self.BUFFER, self.simWindow.height() - self.BUFFER)
        self.simWindow.setScene(self.graphicsScene)

    #draw the food items to the screen and create new food objects
    def drawFood(self, foodAmount):
        for _ in range(foodAmount):
            food_x = randint(self.BUFFER, self.graphicsScene.width() - self.BUFFER)
            food_y = randint(self.BUFFER, self.graphicsScene.height() - self.BUFFER)
            newFood = Food(food_x,food_y)
            self.simulation.addFood(newFood)
            self.graphicsScene.addItem(newFood.pixmap)
            newFood.pixmap.setPos(food_x, food_y)

    #call the correct function based on the simulation state
    def simulate(self):
        self.start()
        self.isSimulating = True
        self.simulationStarted = True

    #start the simulation
    def start(self):
        self.createGraphicsScene()
        self.simulation = Simulation(self.mainWindow)
        self.frameRenderer = FrameRenderer(self.simulation, self.graphicsScene)
        self.drawFood(self.foodSlider.sliderPosition())
        self.frameRenderer.start()

    #toggle whether or not we are current simulating
    def toggleSimulation(self):

        if not self.simulationStarted:
            return

        if self.isSimulating:
            self.frameRenderer.pause()
        else:
            self.frameRenderer.start()

        self.isSimulating = not self.isSimulating

    #clear sim window
    def cancelSimulation(self):
        self.frameRenderer = None
        self.simulation = None
        self.createGraphicsScene()
        self.isSimulating = False
        self.simulationStarted = False

for item in self.graphicsScene.items():
    self.graphicsScene.removeItem(item)